﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;

namespace Template.Core.Log
{
    public class LogAttribute : ILogAttribute
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        private readonly ILogger<LogAttribute> _logger;

        public LogAttribute(IHttpContextAccessor httpContextAccessor, ILogger<LogAttribute> logger)
        {
            _httpContextAccessor = httpContextAccessor;
            _logger = logger;
        }

        /// <summary>
        /// 记录错误信息
        /// </summary>
        /// <param name="ex"></param>
        public void LogError(Exception ex)
        {
            LogMessage logMessage = new LogMessage();
            //存IP地址
            logMessage.IpAddress = _httpContextAccessor.HttpContext.Request.Host.Host;
            //存错误信息
            if (ex.InnerException != null)
                logMessage.LogInfo = ex.InnerException.Message;
            else
                logMessage.LogInfo = ex.Message;
            
            logMessage.StackTrace = ex.StackTrace;
            //存操作时间
            logMessage.OperationTime = DateTime.Now;
            //存角色
            logMessage.OperationName = "admin";
            _logger.LogError(LogHelper.ErrorFormat(logMessage));
        }
    }
}
